package cn.com.callback

import groovy.json.*;
import groovy.swing.impl.DefaultAction
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.crypto.Cipher
import javax.crypto.SecretKey
import javax.crypto.spec.SecretKeySpec
import javax.servlet.RequestDispatcher;
import cn.com.callback.CallBackInvoke
import cn.com.callback.ServiceBackInvoke
import cn.com.elite.EliteBean;
import cn.com.elite.Util;
import java.security.MessageDigest;
import java.sql.ResultSet;
import java.text.ParseException
import java.text.SimpleDateFormat;
import java.time.Instant

import org.apache.commons.codec.binary.Base64
import org.apache.commons.codec.digest.DigestUtils
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import org.json.JSONArray
import org.json.JSONException
import org.json.JSONObject
import cn.com.kh.hst.ThreeDesUtil
import cn.com.kh.KHUtil;
import cn.com.kh.getProperty;


/**
 *
 * @Title: aipHSTMultichannel_dev
 * @Description:华盛证券 服务顾问列表查询 --内部接口
 * @author: TH
 * @date 2021-07-07 17:42:00
 *
 */

public class aipHSTMultichannel_dev implements ServiceBackInvoke {
    private static final Log log = LogFactory.getLog(aipHSTMultichannel_dev.class);

    public String doCallBack(EliteBean eliteBean, HttpServletRequest request, HttpServletResponse response) {

        response.setCharacterEncoding("UTF-8");
        response.setHeader("Access-Control-Allow-Origin", "*");
        String getMethod = request.getMethod();
        log.debug("getMethod:" + getMethod);

        String inData = "";
        String outData = "";
        String totalData = "";
        String dataSourceID = "dataSource";


        BufferedReader iny = null;
        if (getMethod.equals("GET")) {
            inData = request.getParameter("data");
            log.debug("原始Get请求参数:" + inData);
        } else {
            InputStreamReader reader = new InputStreamReader(request.getInputStream(), "UTF-8");
            iny = new BufferedReader(reader);
            String line;
            while ((line = iny.readLine()) != null) {
                inData += line;
            }
            log.debug("原始Post请求参数:" + inData);
        }

        inData = URLDecoder.decode(inData, "UTF-8");
        log.debug("原始inData URLDecoder:" + inData);

        try {

            long startTime = System.currentTimeMillis();
            String reJson = null;
            long endTime = 0;
            JSONObject inObject = new JSONObject(inData);
            //鉴权变量
            String appid = getProperty.get("appid");
            String appsecret = getProperty.get("appsecret");

            //sign加密前后
            String signfront = "";
            String signafter = "";
            def token = GetJV(inObject, "token");

            def updateBeginTime = GetJV(inObject, "updateBeginTime");
            def updateEndTime = GetJV(inObject, "updateEndTime");
            if(updateBeginTime=='' || updateEndTime=='') {
                def selectime=eliteBean.chaxun_sql("SELECT DATE_FORMAT( DATE_SUB(CURDATE(), INTERVAL 1 DAY), '%Y-%m-%d 00:00:00') AS starttime,DATE_FORMAT(NOW(),'%Y-%m-%d 23:59:59') AS endtime","dataSource");
                for (int i = 0; i < selectime.size(); i++) {
                    updateBeginTime = selectime.get(i).get("starttime");
                    updateEndTime = selectime.get(i).get("endtime");
                }
                log.debug("当前时间1：" +updateBeginTime);
                log.debug("当前时间2：" +updateEndTime);
                log.debug("当前时间3：" +selectime);
            }
            String sign_time=Instant.now().getEpochSecond();
            log.debug("解析信息-" +  "sign_time: " + sign_time);

            def pageNo = "1";
            def pageSize = "20";

            HashMap<String, String> paramHashMap = new HashMap<String, String>() {
                {
                    put("token", token);
                    put("sign_time", sign_time);
                    put("pageNo", pageNo);
                    put("pageSize", pageSize);
                    //put("updateBeginTime", updateBeginTime);
                    //put("updateEndTime", updateEndTime);
                }
            };

            log.debug("paramHashMap：" + paramHashMap);
            //自然排序 升序参数
            signfront= ThreeDesUtil.sortMap(paramHashMap,appid,appsecret);
            log.debug("sign加密MD5前：" + signfront);
            signafter = Util.getMD5Str(signfront);
            log.debug("sign加密MD5后：" + signafter);

            //拼接接口入参
            paramHashMap.put("client_key", appid);
            paramHashMap.put("sign", signafter);

            String injson=ThreeDesUtil.SplicingMap(paramHashMap,"&");
            log.debug("injson:" + injson);

            String[] GDSQL = new String[3];
            GDSQL[0] = "DELETE FROM hst_multichannel_his where synchroDate<= DATE_SUB(CURDATE(), INTERVAL 30 DAY)  ";
            GDSQL[1] = "Insert into hst_multichannel_his select * from hst_multichannel where synchroDate<str_to_date(DATE_FORMAT(NOW(),'%Y-%m-%d'),'%Y-%m-%d %H:%i:%s')";
            GDSQL[2] = "delete from hst_multichannel where synchroDate<str_to_date(DATE_FORMAT(NOW(),'%Y-%m-%d'),'%Y-%m-%d %H:%i:%s')";
            def GDresult = eliteBean.updateBatch(GDSQL, "dataSource");

            totalData = Querypromocode(eliteBean, injson,dataSourceID);
            //解析SSO返回信息
            JSONObject jsonObject = new JSONObject(totalData);
            String total = GetJV(jsonObject, "message");
            log.debug("total:" + total);
            double number=Integer.parseInt(total)/Integer.parseInt(pageSize);
            log.debug("number :" + number);
            int count=Math.ceil(number);
            log.debug("count :" + count);

            for (int i = 2; i <=count; i++) {
                //华盛接口连续调用可能异常 添加2S睡眠
                Thread.sleep(2 * 1000);
                pageNo=String.valueOf(i);
                log.debug("pageNo :" + pageNo);
                sign_time=Instant.now().getEpochSecond();
                HashMap<String, String> paramHashMap1 = new HashMap<String, String>() {
                    {
                        put("token", token);
                        put("sign_time", sign_time);
                        put("pageNo", pageNo);
                        put("pageSize", pageSize);
                        //put("updateBeginTime", updateBeginTime);//更新字段开始时间
                        //put("updateEndTime", updateEndTime);//更新字段结束时间
                    }
                };

                log.debug("paramHashMap1：" + paramHashMap1);
                //自然排序 升序参数
                signfront= ThreeDesUtil.sortMap(paramHashMap1,appid,appsecret);
                log.debug("sign加密MD5前：" + signfront);
                signafter = Util.getMD5Str(signfront);
                log.debug("sign加密MD5后：" + signafter);

                //拼接接口入参
                paramHashMap1.put("client_key", appid);
                paramHashMap1.put("sign", signafter);

                String injson1=ThreeDesUtil.SplicingMap(paramHashMap1,"&");
                log.debug("injson1:" + injson1);

                Querypromocode(eliteBean, injson1,dataSourceID);
            }
            /*
            //更新注册渠道的父节点名称
            def Code_Guid,Code_ID,PCode_ID,Code_Name="";
            def level=0;//all渠道等级
            def levelf=0;//某一渠道反向查找等级
            def qdhnumf=0;//某一渠道反向查找结果sql-count
            def getqdhresult = eliteBean.chaxun_sql("select Code_Guid,Code_ID,PCode_ID,level from c_codetables_dev  where 1=1 and Use_Type='渠道类型' ORDER BY level desc","dataSource");
            def qdhnum = getqdhresult.size();
            log.debug("qdhnum:" + qdhnum);
            //all有数据则执行
            if(qdhnum>0){
                for(int i=0;i<qdhnum;i++) {
                    def tempname="";
                    Code_Guid = getqdhresult.get(i).get("Code_Guid");
                    Code_ID = getqdhresult.get(i).get("Code_ID");
                    PCode_ID = getqdhresult.get(i).get("PCode_ID");
                    level = getqdhresult.get(i).get("level");
                    log.debug(i+"Code_Guid:" + Code_Guid+"	,Code_ID:"+Code_ID+"	,PCode_ID:"+PCode_ID+"	,level:"+level);
                    //判断当前查询的渠道等级
                    if(level>1){
                        int j=0;
                        //父节点不为空则不断查找
                        while (PCode_ID!=null) {
                            j++;
                            log.debug("j:"+j);
                            def getqdhfresult = eliteBean.chaxun_sql("select PCode_ID,Code_Name,level as levelf from c_codetables_dev  where 1=1 and Use_Type='渠道类型' and Code_ID='"+PCode_ID+"' and length(level)>0","dataSource");
                            qdhnumf = getqdhfresult.size();
                            //判断节点之上还有嘛
                            if(qdhnumf>0){
                                levelf = getqdhfresult.get(0).get("levelf");
                                PCode_ID = getqdhfresult.get(0).get("PCode_ID");
                                Code_Name = getqdhfresult.get(0).get("Code_Name");
                                //非父节点则拼接，否则等于上次拼接结果
                                if(levelf>1){
                                    tempname = Code_Name+","+tempname;
                                }else{
                                    tempname=tempname;
                                }
                            }else{
                                PCode_ID=null;
                            }
                            log.debug(j+"PCode_ID:"+PCode_ID+"	,Code_Name:"+Code_Name+"	,tempname:"+tempname+"	,levelf:"+levelf);
                        }
                        //截取最后一个符号，
                        log.debug("tempname.length():"+tempname.length());
                        if(tempname.length()>1){
                            tempname=tempname.substring(0,tempname.length()-1);
                        }
                        log.debug("update-tempname:"+tempname);
                        eliteBean.update("update c_codetables_dev set Parentpath = '"+tempname+"' where 1=1 and Use_Type='渠道类型' and Code_Guid='"+Code_Guid+"' ", "dataSource");
                    }

                }
                //批量更新 渠道一级 二级
                eliteBean.update("update c_codetables_dev set Parent1 = SUBSTRING_INDEX(Parentpath, ',', 1),Parent2=case when  instr(Parentpath,',')=0 then '' else REPLACE(SUBSTRING_INDEX(Parentpath, ',', 2),CONCAT(SUBSTRING_INDEX(Parentpath, ',', 1),','),'') end where 1=1 and Use_Type='渠道类型' ", "dataSource");
            }
            */

            //批量更新 渠道的归属大类 一级 二级 id
            eliteBean.update("update c_codetables_dev set Parent1 = SUBSTRING_INDEX(Parentpath, ',', 1),Parent2=case when  instr(Parentpath,',')=0 then '' else REPLACE(SUBSTRING_INDEX(Parentpath, ',', 2),CONCAT(SUBSTRING_INDEX(Parentpath, ',', 1),','),'') end where 1=1 and Use_Type='渠道类型' ", "dataSource");

            //批量更新 渠道的归属大类 一级 二级 名称
            eliteBean.update("UPDATE c_codetables_dev k left JOIN c_codetables_dev a ON k.Parent1 = a.Code_ID and a.Use_Type='渠道结构' left JOIN c_codetables_dev b ON k.Parent2 = b.Code_ID and b.Use_Type='渠道结构' SET k.Parent1 =a.Code_Name,k.Parent2 =b.Code_Name WHERE 1=1 and k.Use_Type='渠道类型' ", "dataSource");

            outData = "{\"result\":\"1\",\"message\":\"处理成功\",\"data\":[]}";

        } catch (Exception e) {
            log.error("接口处理异常" + e.getMessage());
            // 失败返回
            outData = "{\"result\":\"-1\",\"message\":\"处理失败(" + e.getMessage() + ")\",\"data\":[]}";
        }

        return outData;
    }

    //
    public static String Querypromocode(EliteBean eliteBean , String injson, String dataSourceID) {

        long startTime = System.currentTimeMillis();
        log.debug("处理开始时间:" + startTime);

        long endTime = System.currentTimeMillis();

        String reJson = null;
        try {

            String doURL = getProperty.get("HSTURL");
            doURL = doURL+"/admin/member/query-channel";
            log.debug("doURL:" + doURL);
            Map<String, String> headMap = new HashMap<String, String>();
            headMap.put("Content-Type", "application/x-www-form-urlencoded");
            def getResult = Util.doHttpPostUseHead(doURL, injson, "UTF-8", 10000, 0, headMap);
            log.debug("getResult:" + getResult);
            UUID uuid = UUID.randomUUID();

            //解析SSO返回信息
            JSONObject jsonObject = new JSONObject(getResult);
            String code = GetJV(jsonObject, "code");
            String result = GetJV(jsonObject, "result");
            JSONObject dataObject;

            log.debug("code:" + code);
            if(code == "00000") {
                dataObject = new JSONObject(result);
                String rows = GetJV(dataObject, "rows");
                String total = GetJV(dataObject, "total");
                log.debug('rows'+rows);
                log.debug('total'+total);

                SimpleDateFormat dateformat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                String dateStr = dateformat.format(System.currentTimeMillis());

                JSONArray arrJsonArray = new JSONArray(rows);
                int arrInt = arrJsonArray.length();
                for (int i = 0; i < arrInt; i++) {
                    JSONObject arrSmsJson = arrJsonArray.getJSONObject(i);
                    String id =GetJV(arrSmsJson,"id");//渠道id
                    String parentId=GetJV(arrSmsJson,"parentId");//上级渠道id
                    if(parentId=="-1"){
                        parentId="NULL";
                    }else{
                        parentId="'"+parentId+"'";
                    }
                    String level =GetJV(arrSmsJson,"level");//层级
                    String maskId =GetJV(arrSmsJson,"maskId");//maskid id
                    String name =GetJV(arrSmsJson,"name");//名称
                    String description =GetJV(arrSmsJson,"description");//描述
                    String superIds=GetJV(arrSmsJson,"superIds");//上层所有渠道（parentId+","+id）
                    String createdDate =GetJV(arrSmsJson,"createdDate");//创建时间
                    String createdUser =GetJV(arrSmsJson,"createdUser");//创建人
                    String updatedDate =GetJV(arrSmsJson,"updatedDate");//更新时间
                    String updatedUser =GetJV(arrSmsJson,"updatedUser");//更新人
                    String parentInfos =GetJV(arrSmsJson,"parentInfos");//父级结构信息 List

                    if (parentInfos == null || parentInfos.size() == 0 ||parentInfos == "") {
                        //list为空
                        log.debug(name + ":当前渠道无父级结构信息："+id);
                    } else {
                        //list不为空
                        JSONArray parentInfosArray = new JSONArray(parentInfos);
                        int parentInfosInt = parentInfosArray.length();
                        for (int j = 0; j < parentInfosInt; j++) {
                            JSONObject parentInfosJson = parentInfosArray.getJSONObject(j);
                            String p_id =GetJV(parentInfosJson,"id");//组织架构 ID
                            String p_parentId =GetJV(parentInfosJson,"parentId");//上级组织架构 ID
                            String p_level =GetJV(parentInfosJson,"level");//层级
                            String p_name =GetJV(parentInfosJson,"name");//名称
                            //查询是否存在
                            def selectresult=eliteBean.chaxun_sql("select Code_id from c_codetables_dev where code_id='"+p_id+"' and Use_Type='渠道结构'","dataSource");
                            if(selectresult.size()>0) {//存在则更新
                                def updateresult = eliteBean.update(
                                        "UPDATE c_codetables_dev SET PCode_ID = "+p_parentId+", Code_Name = '"+p_name+"', Use_Status = '1', Modifiedby ='SELITE' , Modifieddate = now(),level = '"+p_level+"' WHERE Code_id = '"+p_id+"' and  Use_Type = '渠道结构'", "dataSource");
                            }else {//否则则新增
                                def insertresult = eliteBean.update(
                                        "INSERT INTO c_codetables_dev (Code_Guid, Code_ID, PCode_ID, Code_Name, Use_Type, Use_Status, Createdby, Createddate, Modifiedby, Modifieddate,  level) VALUES (UUID(),'"+p_id+"',"+p_parentId+",'"+p_name+"','渠道结构','1','SELITE',now(),'SELITE',now(),'"+level+"')", "dataSource");
                            }
                        }

                    }

                    log.debug(name + ":name");
                    log.debug(id + ":id");
                    def dataresult = eliteBean.update(
                            "insert into hst_multichannel (id, parentId, level, maskId, name, description, superIds, createdDate, createdUser, updatedDate, updatedUser,synchroDate) VALUES ('"+id+"',"+parentId+",'"+level+"','"+maskId+"','"+name+"','"+description+"','"+superIds+"','"+createdDate+"','"+createdUser+"','"+updatedDate+"','"+updatedUser+"',now())", "dataSource");
                    def selectresult=eliteBean.chaxun_sql("select Code_id from c_codetables_dev where code_id='"+id+"' and Use_Type='渠道类型'","dataSource");
                    if(selectresult.size()>0) {
                        def updateresult = eliteBean.update(
                                "UPDATE c_codetables_dev SET PCode_ID = "+parentId+", Code_Name = '"+name+"', Parentpath = '"+superIds+"', Use_Status = '1', Modifiedby ='SELITE' , Modifieddate = now(),level = '"+level+"' WHERE Code_id = '"+id+"' and  Use_Type = '渠道类型'", "dataSource");
                    }else {
                        def insertresult = eliteBean.update(
                                "INSERT INTO c_codetables_dev (Code_Guid, Code_ID, PCode_ID, Code_Name, Parentpath, Use_Type, Use_Status, Createdby, Createddate, Modifiedby, Modifieddate,  level) VALUES (UUID(),'"+id+"',"+parentId+",'"+name+"','"+superIds+"','渠道类型','1','SELITE',now(),'SELITE',now(),'"+level+"')", "dataSource");
                    }

                }
                reJson = "{\"result\":\"1\",\"message\":"+total+"}";

            }else {
                String msg = GetJV(jsonObject, "msg");
                reJson = "{\"result\":\"-1\",\"message\":\"用户获取失败(" + msg + ")\"}";
            }

        } catch (Exception e) {
            log.error("接口处理异常" + e.getMessage());
            // 失败返回
            reJson = "{\"result\":\"-1\",\"message\":\"接口异常\"}";
        }
        return reJson;
    }


    // 解析Json值
    public static String GetJV(JSONObject inJson, String getKey) {
        String Rev_Value = null;
        try {
            Rev_Value = inJson.getString(getKey);
        } catch (Exception e) {
            try {
                Rev_Value = String.valueOf(inJson.getInt(getKey));
            } catch (Exception e1) {
                try {
                    Rev_Value = String.valueOf(inJson.getJSONArray(getKey));
                } catch (Exception e2) {
                    try {
                        Rev_Value = String.valueOf(inJson.getJSONObject(getKey));
                    } catch (Exception e3) {
                        Rev_Value = "";
                    }
                }
            }
        } finally {
            if (Rev_Value == null || Rev_Value.equals("null") || Rev_Value.length() <= 0) {
                Rev_Value = "";
            } else {
            }
        }
        log.debug("解析-k=" + getKey + " v=" + Rev_Value);
        return Rev_Value;
    }


    // 非空校验isNull
    public static boolean isNull(String value) {

        boolean reFlag = true;
        if (value == "" || value.length() <= 0) {
            reFlag = true;
        } else {
            reFlag = false;
        }
        log.debug(reFlag);
        return reFlag;
    }

    // 非空校验isNullMSG
    public static String isNullMSG(String key, String value) {

        String reResult = "";
        if (value == "" || value.length() <= 0) {
            reResult = key + "必填字段;";
        }
        return reResult;
    }

}
